package com.zwg.mode.mvp

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.zwg.mode.R
import com.zwg.mode.R.layout.activity_main

/**
 * View 层
 * 只负责对UI的数据更新
 * 相关的监听
 * 对controller层发起动作
 */
class MVPLoginActivity : AppCompatActivity(), LoginPresenter.OnCheckUserNameStateResultCallback,
    LoginPresenter.OnDoLoginStateChange {
    lateinit var loginBtn: Button
    lateinit var accountInputBox: EditText
    lateinit var passwordInputBox: EditText
    lateinit var loginTipsText: TextView

    private val loginController by lazy {
        LoginPresenter()
    }

    private var isUserNameCanbeus = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activity_main)
        initView()
        initListener()


    }

    private fun initView() {
        loginBtn = findViewById(R.id.loginBtn)
        accountInputBox = findViewById(R.id.accountInputBox)
        passwordInputBox = findViewById(R.id.passwordInputBox)
        loginTipsText = findViewById(R.id.loginTipsText)

    }

    private fun initListener() {

        loginBtn.setOnClickListener {
            // 登录逻辑
            tologin()
        }
        //监听内容变化
        accountInputBox.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //TODO 检查当前账号是否有注册掉
                loginController.checkUserNameState(s.toString(), this@MVPLoginActivity)
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
    }

    /**
     * 处理登录逻辑
     */
    private fun tologin() {
        //给密码加盐
        if (!isUserNameCanbeus) {
            ///提示用户说当前用户名已经被注册了
            return
        }
        //做登录的逻辑处理
        val accout = accountInputBox.text.toString()
        val password = passwordInputBox.text.toString()
        loginController.doLogin(accout, password, this)
    }

    override fun onAccountFormatError() {
        loginTipsText.text = "账号不可为空..."
    }

    override fun onPasswordEmpty() {
        loginTipsText.text = "密码不可为空..."
    }

    override fun onLoading() {
        loginTipsText.text = "登录中..."
    }

    override fun onLoginSuccess() {
        loginTipsText.text = "登录成功..."
    }

    override fun onLoginFailed() {
        loginTipsText.text = "登录失败..."
    }

    override fun onNotExist() {
        //TODO 用户名可用
        loginTipsText.text =
            "用户名可用"
        this.isUserNameCanbeus = true
    }

    override fun onExist() {
        //TODO 用户名不可用
        loginTipsText.text =
            "用户名已经注册"
        this.isUserNameCanbeus = false
    }
}